package com.sbs.gaoxinqutoilet.fragment;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.TrafficStats;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.activity.LoginActivity;
import com.sbs.gaoxinqutoilet.base.BaseBackFragment;
import com.sbs.gaoxinqutoilet.entity.LogOutResult;
import com.sbs.gaoxinqutoilet.eventbus.EventCenter;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.Constants;
import com.sbs.gaoxinqutoilet.interfaces.DialogClick;
import com.sbs.gaoxinqutoilet.interfaces.EventConstant;
import com.sbs.gaoxinqutoilet.store.PersistentCookieStore;
import com.sbs.gaoxinqutoilet.utils.GlideCacheUtil;
import com.sbs.gaoxinqutoilet.utils.GsonTools;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.SPUtil;
import com.sbs.gaoxinqutoilet.utils.ToastUtils;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by 聪明一只哈 on 2018/6/4.
 * Time: 2018/6/4  17:37
 */

public class SettingFragment extends BaseBackFragment {


    @BindView(R.id.toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_iv_menu)
    ImageView toolbarIvMenu;
    @BindView(R.id.toolbar_tv_menu)
    TextView toolbarTvMenu;
    @BindView(R.id.toolbar_rl_menu)
    AutoRelativeLayout toolbarRlMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.bt_clear_image_data)
    TextView btClearImageData;
    @BindView(R.id.tv_set_cache_image_data)
    TextView tvSetCacheImageData;
    @BindView(R.id.tv_set_desc)
    TextView tvSetDesc;
    @BindView(R.id.tv_up_d)
    TextView tvUpD;
    @BindView(R.id.tv_down_d)
    TextView tvDownD;
    @BindView(R.id.tv_show_date)
    TextView tv_Show_Date;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.bt_setting_finish)
    Button bt_setting_finish;
    Unbinder unbinder;
    private String versionName;
    private int versioncode;
    private String token_data;

    public static SettingFragment newInstance() {
        Bundle args = new Bundle();
        SettingFragment fragment = new SettingFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_setting, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView(inflater);

        return attachToSwipeBack(view);
    }


    /**
     * 初始化view
     *
     * @param inflater
     */
    private void initView(LayoutInflater inflater) {
        EventBus.getDefault().register(this);
        toolbarTitle.setText("设置");
        //返回按钮
        toolbarBack.setVisibility(View.VISIBLE);
        //设置回键
        initToolbarBack(toolbar);

        token_data = SPUtil.getString(Constants.KEY_TOKEN, "");

        showLoadingDialog();


        try {
            PackageManager pm = _mActivity.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(_mActivity.getPackageName(), 0);
            versionName = pi.versionName;
            versioncode = pi.versionCode;

            tvVersion.setText("当前版本为:" + versionName + "." + versioncode);
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }

    }




    /**
     * 页面加载动画结束就调用
     *
     * @param savedInstanceState
     */
    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);

        // 缓存
        if (tvSetCacheImageData != null) {
            tvSetCacheImageData.setText(GlideCacheUtil.getInstance().getCacheSize(getActivity()));
        }
        //上一次清理日期
        String clear_time = SPUtil.getString("clear_time", "");

        LogUtils.i("datetest", "onEnterAnimationEnd: " + clear_time);
        if (!TextUtils.isEmpty(clear_time) && clear_time != null) {
            tv_Show_Date.setText("" + clear_time);
        } else {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            SPUtil.putString("clear_time", format);
            tv_Show_Date.setText("" + format);
        }

        //流量上传下载
        getUpAndDownload();
        //getUpAndDownloadOther();

//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                cancelLoadingDialog();
//            }
//        }, 1000);

    }

    private void getUpAndDownloadOther() {
        //1.获取一个包管理器。
        PackageManager pm = _mActivity.getPackageManager();
//2.遍历手机操作 获取所有的应用程序的uid
        List<ApplicationInfo> appliactaionInfos = pm.getInstalledApplications(0);
        for (ApplicationInfo applicationInfo : appliactaionInfos) {
            int uid = applicationInfo.uid;    // 获得软件uid
            //proc/uid_stat/10086
            long tx = TrafficStats.getUidTxBytes(uid);//发送的 上传的流量byte
            long rx = TrafficStats.getUidRxBytes(uid);//下载的流量 byte
            //方法返回值 -1 代表的是应用程序没有产生流量 或者操作系统不支持流量统计

            LogUtils.i("流量", "uid:" + uid + "~~~ 上传:" + tx + "~~~ 下载:" + rx);
        }
        TrafficStats.getMobileTxBytes();//获取手机3g/2g网络上传的总流量
        TrafficStats.getMobileRxBytes();//手机2g/3g下载的总流量

        TrafficStats.getTotalTxBytes();//手机全部网络接口 包括wifi，3g、2g上传的总流量
        TrafficStats.getTotalRxBytes();//手机全部网络接口 包括wifi，3g、2g下载的总流量
    }

    /**
     * 流量上传下载
     */
    private void getUpAndDownload() {
        PackageManager pm = _mActivity.getPackageManager();             //拿到包管理者
        //拿到包的信息  PackageInfo是系统的一个类
        List<PackageInfo> info = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES
                | PackageManager.GET_PERMISSIONS);
        List<Map<String, String>> appInfo = new ArrayList<>();//用于存放App的名称，上传和下载的字节
        /**
         * 通过看它有没有网络权限权限
         */
//        for (PackageInfo temp : info) {
//            String permissions[] = temp.requestedPermissions;    //拿到该包的权限
//            if (permissions != null && permissions.length > 0) {   //如果有权限
//                for (String p : permissions) {
//                    if (p.equals("android.permission.INTERNET")) {//是否有网络权限
//                        String appName = temp.applicationInfo.loadLabel(pm).toString();       //App名称
//                        long appMrb = TrafficStats.getUidRxBytes(temp.applicationInfo.uid);//App接收的字节
//                        long appMtb = TrafficStats.getUidTxBytes(temp.applicationInfo.uid);//App发送的字节
//                        String str = appName + "下载：" + byteToMB(appMrb) + "上传:" + byteToMB(appMtb);
//                        LogUtils.i("流量", str);
//                        Map<String, String> map = new HashMap<>();
//                        map.put("info", str);
//                        appInfo.add(map);
//                    }
//                }
//            }
//        }

        for (PackageInfo temp : info) {
            String appName = temp.applicationInfo.loadLabel(pm).toString();       //App名称
            long appMrb = TrafficStats.getUidRxBytes(temp.applicationInfo.uid);//App接收的字节
            long appMtb = TrafficStats.getUidTxBytes(temp.applicationInfo.uid);//App发送的字节
            String str = appName + "下载：" + byteToMB(appMrb) + "上传:" + byteToMB(appMtb);

            String app_name = getResources().getString(R.string.app_name);
            if (app_name.equals(appName)) {
                LogUtils.i("流量", str);
                tvUpD.setText("" + byteToMB(appMtb));
                tvDownD.setText("" + byteToMB(appMrb));
                cancelLoadingDialog();
                break;
            }
        }
    }


    //将字节数转化为MB
    private String byteToMB(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size > kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else {
            return String.format("%d B", size);
        }
    }


//    @OnClick(R.id.bt_clear_image_data)
//    public void onViewClicked() {
//        showClearDialog();
//
//    }

    @OnClick({R.id.bt_clear_image_data, R.id.bt_setting_finish,R.id.tv_version,R.id.tv_up_d})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_clear_image_data:
                showClearDialog();
                break;
            case R.id.bt_setting_finish:

//                SPUtil.remove(Constants.LOGINNAME);
//                SPUtil.remove(Constants.LOGINPASS);
//                SPUtil.remove(Constants.KEY_USER);
//
//                PersistentCookieStore store = new PersistentCookieStore(_mActivity.getApplicationContext());
//                store.removeAll();
//                Intent intent = new Intent();
//                intent.setClass(getActivity(), LoginActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
//                _mActivity.finish();

                //关闭 mianActivity
                //EventBus.getDefault().post(new EventCenter(EventConstant.FINISH_MAIN_AC));
                String out_url= HttpApis.logOut;

                String token_data = SPUtil.getString(Constants.KEY_TOKEN, "");
                HashMap<String, String> map = new HashMap<>();
                map.put("token",token_data);

                HttpUtils.requestGet(_mActivity,out_url,map,new Request(){
                    @Override
                    public void success(String jsonStr) {
                        super.success(jsonStr);
                        //{"result":"1"}
                        LogUtils.i("LogOut",jsonStr);
                        LogOutResult logOutResult = GsonTools.changeGsonToBean(jsonStr, LogOutResult.class);

                        if(logOutResult!=null&&"1".equals(logOutResult.getResult())){
                            SPUtil.remove(Constants.LOGINNAME);
                            SPUtil.remove(Constants.LOGINPASS);
                            SPUtil.remove(Constants.KEY_USER);
                            SPUtil.remove(Constants.KEY_TOKEN);

                            PersistentCookieStore store = new PersistentCookieStore(_mActivity.getApplicationContext());
                            store.removeAll();
                            Intent intent = new Intent();
                            intent.setClass(getActivity(), LoginActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            _mActivity.finish();
                        }else{
                            ToastUtils.showLongToast(_mActivity,"退出失败");
                        }

                    }

                    @Override
                    public void error(String error) {
                        super.error(error);
                        LogUtils.i("LogOut",error);
                    }
                });


                break;

            case R.id.tv_version:
                Toast.makeText(_mActivity, "这是当前版本号", Toast.LENGTH_SHORT).show();
                Toast.makeText(_mActivity, "测试补丁更新第一次", Toast.LENGTH_SHORT).show();

                break;

            case R.id.tv_up_d:
                Toast.makeText(_mActivity, "测试补丁更新第一次", Toast.LENGTH_SHORT).show();

                break;
        }
    }

    // 清楚图片缓存
    private void showClearDialog() {
        showAlertDialogNoMsg(getActivity(), "确定清除图片缓存？", "", new DialogClick() {
            @Override
            public void PositiveMessage() {
                GlideCacheUtil.getInstance().clearImageAllCache(getActivity());
                showShortToast("清除成功");
                tvSetCacheImageData.setText("0.0Byte");
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String formats = sdf.format(date);
                SPUtil.putString("clear_time", formats);
                tv_Show_Date.setText("" + formats);
            }

            @Override
            public void NegativeMessage() {

            }
        });
    }


    /**
     * eventbus 页面跳转,事件接受
     *
     * @param center
     */
    @Subscribe
    public void onEventReceive(EventCenter center) {

        if (center.getEventCode() == EventConstant.UPLOAD_BUY_MODIFY) {
            //提交成功
            LogUtils.e("显示", "刷新");


            new Handler() {
            }.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //requestRefresh();

                    //Toast.makeText(_mActivity, "接受跳转", Toast.LENGTH_SHORT).show();
                }
            }, 500);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        cancelLoadingDialog();
        EventBus.getDefault().unregister(this);
        OkHttpUtils.getInstance().cancelTag(this);
    }



}
